package zen2d;

import java.awt.*;
import java.awt.event.KeyEvent;

public abstract class Sprite implements KeyEventListener, MouseEventListener {

    protected int x, y, width, height;

    protected boolean live = true;

    public static int HORIZONTAL_SIZE = 20;

    public Sprite(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;

    }

    public boolean isLive() {
        return live;
    }

    protected void setLive(boolean live) {
        this.live = live;
    }

    public void endLive() {
        if (!isLive()) {
            return;
        }
        setLive(false);
        afterEndLive();
    }

    protected void afterEndLive() {
        dispose();
    }

    protected void dispose() {
        Zen2d.removeSprite(this);
    }

    public Rectangle getBounds() {
        return new Rectangle(x, y, width, height);
    }

    private void setBounds(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;

    }

    public void setLocation(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public Point getLocation() {
        return new Point(x, y);
    }


    protected abstract void update();

    protected abstract void draw(GraphicsContext graphicsContext);


    @Override
    public void keyDown(int keyCode) {
        switch (keyCode) {
            case KeyEvent.VK_LEFT: {
                left();
            }
            break;
            case KeyEvent.VK_RIGHT: {
                right();
            }
            break;
            case KeyEvent.VK_UP: {
                up();
            }
            break;
            case KeyEvent.VK_DOWN: {
                down();
            }
            break;
            case KeyEvent.VK_SPACE: {
                space();
            }
            break;
        }
    }

    protected abstract void up();

    protected abstract void down();

    protected abstract void left();

    protected abstract void right();

    protected abstract void space();

    @Override
    public void keyUp(int keyCode) {

    }

    protected void borderDetection() {
        if (x <= 0) {
            x = 0;
        }
        if (y <= 0) {
            y = 0;
        }
        if (x >= Zen2d.WIDTH - this.width) {
            x = Zen2d.WIDTH - this.width;
        }
        if (y >= Zen2d.HEIGHT - this.height) {
            y = Zen2d.HEIGHT - this.height;
        }
    }

    public boolean isSameHorizontal(Sprite sprite) {

        Rectangle rectangle = sprite.getBounds();
        return (rectangle.y + rectangle.height >= y + height - HORIZONTAL_SIZE) && (rectangle.y + rectangle.height <= y + height);
    }


}
